/**
 * Copyright(c)2012 Beijing PeaceMap Co.,Ltd.
 * All right reserved. 
 */
package com.pmc.dwa.common.dialect;

/**
 * @description 数据库方言通用接口
 * @author aokunsang
 * @date 2013-1-6
 */
public abstract class Dialect {
	
	public final static String SELECT = "select";
	public final static String SELECT_DISTINCT = "select distinct";
	public final static String COUNT_FIELD = "total";
	
	/**
	 * 获取分页SQL语句
	 * @param sql The SQL statement to base the limit query off of.
     * @param offset Offset of the first row to be returned by the query (zero-based)
     * @param limit Maximum number of rows to be returned by the query
     * @return A new SQL statement with the LIMIT clause applied.
	 */
	public abstract String getLimitString(String sql, int offset, int limit);
	/**
	 * 获取总条数的SQL语句[该方法通用]
	 * @param sql
	 * @return
	 */
	public String getCountString(String sql){
    	
    	StringBuilder sb = new StringBuilder(sql.trim());

        String querySqlLowered = sql.trim().toLowerCase();
        int orderByIndex = querySqlLowered.toLowerCase().indexOf("order by");
//        String orderby = orderByIndex > 0 ? sql.substring(orderByIndex) : "ORDER BY CURRENT_TIMESTAMP";

        // Delete the order by clause at the end of the query
        if (orderByIndex > 0) {
            sb.delete(orderByIndex, orderByIndex + sql.substring(orderByIndex).length());
        }
        
        String querySqlFrom = sb.toString().toLowerCase();
        int fromIndex = querySqlFrom.indexOf("from");
        if(fromIndex > 0){
        	sb.delete(0, fromIndex);
        }
    	sb.insert(0, "select count(1) as " + COUNT_FIELD + " ");
    	return sb.toString();
    }
}
